package com.weaver.qfengx.api.edoc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.weaver.qfengx.DaoUtils;
import com.weaver.qfengx.DateUtils;
import com.weaver.qfengx.LogUtils;
import com.weaver.qfengx.StringUtils;
import com.weaver.qfengx.okhttp.body.RequestJsonBody;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class ReqLogInterceptor implements Interceptor {

    private static final LogUtils log = new LogUtils(ReqLogInterceptor.class);

    private String logTable;

    public ReqLogInterceptor(String logTable) {
        this.logTable = logTable;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        LogEntity logEntity = new LogEntity();
        long start = System.currentTimeMillis();
        logEntity.setCreatetime(DateUtils.datetime());
        logEntity.setMethod(request.method());
        logEntity.setUrl(request.url().toString());
        if (StringUtils.equalsIgnoreCase(request.method(), "post")) {
            // 处理json body体
            if (request.body() instanceof RequestJsonBody) {
                logEntity.setParamstr(((RequestJsonBody) request.body()).getJsonContent());
            }
        } else if (StringUtils.equalsIgnoreCase(request.method(), "get")) {
            HttpUrl oldHttpUrl = request.url();
            Map<String, String> oldParams = Maps.newHashMap();
            for (Object key : oldHttpUrl.queryParameterNames()) {
                oldParams.put(key.toString(), oldHttpUrl.queryParameter(key.toString()));
            }
            logEntity.setParamstr(JSON.toJSONString(oldParams));
        }
        Response resp = chain.proceed(request);
        // 添加请求头
        Headers headers = request.headers();
        Map<String, String> headerMap = Maps.newHashMap();
        for (Object key : headers.names()) {
            headerMap.put(StringUtils.val(key), headers.get(StringUtils.val(key)));
        }
        logEntity.setHeaders(JSON.toJSONString(headerMap));
        logEntity.setHttpcode(Integer.toString(resp.code()));
        logEntity.setRepstr(getResponseStr(resp));
        logEntity.setResponsetime(DateUtils.datetime());
        logEntity.setErrorcode(JSONObject.parseObject(logEntity.getRepstr()).getString("code"));
        logEntity.setErrmsg(JSONObject.parseObject(logEntity.getRepstr()).getString("msg"));
        logEntity.setCosttime(Long.toString(System.currentTimeMillis() - start));
        if (StringUtils.isNotEmpty(logTable)) {
            try {
                DaoUtils.saveBean(logTable, logEntity);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        System.out.println(logEntity);
        return resp;
    }

    private static String getResponseStr(Response response) {
        try {
            ResponseBody responseBody = response.peekBody(1024 * 1024);
            return responseBody.string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}
